//
//  AppointmentDetailsController.swift
//  puretennis
//
//  Created by IYE Technologies on 1/15/15.
//  Copyright (c) 2015 IYE Technologies. All rights reserved.
//

import UIKit

class AppointmentDetailsController: UIViewController {
    
    @IBOutlet weak var dateTimeLabel: UILabel!
    
    var inviteesTitleLabel:UILabel!
    var inviteesScrollView: AppointmentScrollView?
    
    var participantsTitleLabel:UILabel!;
    var participantsScrollView: AppointmentScrollView!
    
    var requestsTitleLabel:UILabel!;
    var requestScrollView: AppointmentScrollView?
    
    var noteTextView: UITextView!
    
    var appointmentGuid:String!;
    
    var ownerGuid:String!;
    
    var bottomMenu:UIView?;
    
    override func viewDidLoad() {
        super.viewDidLoad();
        ViewUtils.addBackgroundView(self);
        self.initNavigation();
        self.loadAppointmentDetails();
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated);
        self.hideTabBar();
    }
    
    func setAppointmentGuid(appointmentGuid:String){
        self.appointmentGuid = appointmentGuid;
    }
    
    func loadAppointmentDetails(){
        self.processing();
        let url = "/api/v1/appointment/\(self.appointmentGuid)";
        HttpUtils.sendRequest(url, method: RequestMethod.GET, httpBody: nil, successHandle: { (response) -> Void in
            var appointment = response as NSMutableDictionary;
            var appointmentGuid = appointment.objectForKey("guid") as String;
            var owner = appointment.objectForKey("owner") as NSDictionary;
            self.ownerGuid = owner.objectForKey("guid") as String;
            var location = appointment.objectForKey("location") as String;
            
            self.navigationItem.titleView = ViewUtils.titleView(location);
            
            var date = appointment.objectForKey("date") as String;
            var periods = appointment.objectForKey("periods") as [String];
            self.dateTimeLabel.text = "\(date)\t\(periods[0]) - \(periods[1])";
            
            var invitations = appointment.objectForKey("invitations") as [NSDictionary];
            if(invitations.count > 0){
                self.addInvitationScrollView();
                self.inviteesScrollView!.addElements(appointmentGuid,ownerGuid: self.ownerGuid,elements: invitations, dropTargetView: nil, type: ContainerType.Invitees);
            }
            
            var participants = appointment.objectForKey("participants") as [NSDictionary];
            if(participants.count > 0){
                self.addParticipantsScrollView();
                self.participantsScrollView.addElements(appointmentGuid,ownerGuid: self.ownerGuid,elements: participants, dropTargetView: nil, type: ContainerType.Participants);
            }
            
            var dropTargetView:AppointmentScrollView?;
            var isOwner = (Utils.currentUserGuid() == self.ownerGuid);
            if(isOwner){
                self.setChoiceNavigationBarItem();
                dropTargetView = self.participantsScrollView;
            }
            var requests = appointment.objectForKey("requests") as [NSDictionary];
            if(requests.count > 0){
                self.addRequestsScrollView();
                self.requestScrollView!.addElements(appointmentGuid,ownerGuid: self.ownerGuid,elements: requests, dropTargetView: dropTargetView, type: ContainerType.Requests);
            }
            
            var canOperationInvitation = appointment.objectForKey("canOperationInvitation") as Bool;
            if(canOperationInvitation){
                self.setInvitationOperation();
            }
            
            var canSendJoinRequest = appointment.objectForKey("canSendJoinRequest") as Bool;
            if(canSendJoinRequest){
                self.setSendJoinRequestOperation();
            }
            
            var canLeave = appointment.objectForKey("canLeave") as Bool;
            if(canLeave){
                self.setLeaveAppointmentOperation();
            }
            
            var paymentWay = appointment.objectForKey("paymentWay") as String;
            var note = appointment.objectForKey("note") as String;
            
            var noteText = "\(paymentWay)\n\n\(note)"
            self.fillNoteTextView(noteText);
            
            self.processComplete();
            }, errorHandle: { (error) -> Void in
            self.processComplete();
        });

    }
    
    func addInvitationScrollView(){
        var verticalMargin:CGFloat = 10;
        var marginLeft:CGFloat = 5;
        var width = self.view.frame.width - (marginLeft * 2);
        var origin = CGPoint(x: marginLeft, y: self.dateTimeLabel.frame.origin.y + self.dateTimeLabel.frame.height + verticalMargin);
        
        self.inviteesTitleLabel = self.setTitleLabel("邀请加入的小伙伴", origin: origin);
        self.view.addSubview(self.inviteesTitleLabel);
        
        origin.y += (self.inviteesTitleLabel.frame.height + 2);
        
        var size = CGSize(width: self.view.frame.width - (marginLeft * 2), height: self.view.frame.height * 0.16);
        var frame = CGRect(origin: origin, size: size);
        self.inviteesScrollView = AppointmentScrollView(frame: frame);
        self.inviteesScrollView?.ownerGuid = self.ownerGuid;
        self.view.addSubview(self.inviteesScrollView!);
    }
    
    func adjustParticipantsPosition(){
        var participantsScrollViewOriginalOrigin = self.participantsScrollView.frame.origin;
        
        var titleLableOrigin = self.inviteesTitleLabel.frame.origin;
        self.participantsTitleLabel.frame.origin = titleLableOrigin;
        self.inviteesTitleLabel?.removeFromSuperview();
        self.inviteesTitleLabel = nil;
        
        var scrollViewNewOrigin = self.inviteesScrollView!.frame.origin;
        self.participantsScrollView.frame.origin = scrollViewNewOrigin;
        self.inviteesScrollView?.removeFromSuperview();
        self.inviteesScrollView = nil;
        
    }
    
    func addParticipantsScrollView(){
        var marginTop:CGFloat = 5;
        var marginLeft:CGFloat = 5;
        var width = self.view.frame.width - (marginTop * 2);
        
        var originY:CGFloat!;
        if(self.inviteesScrollView == nil){
            originY = self.dateTimeLabel.frame.origin.y + self.dateTimeLabel.frame.height + 10;
        } else {
            originY = self.inviteesScrollView!.frame.origin.y + self.inviteesScrollView!.frame.height + marginTop;
        }
        
        var origin = CGPoint(x: marginLeft, y: originY);
        
        self.participantsTitleLabel = self.setTitleLabel("已经加入的小伙伴", origin: origin);
        self.view.addSubview(self.participantsTitleLabel);
        
        origin.y += (self.participantsTitleLabel.frame.height + 2);
        
        var size = CGSize(width: self.view.frame.width - (marginLeft * 2), height: self.view.frame.height * 0.16);
        var frame = CGRect(origin: origin, size: size);
        self.participantsScrollView = AppointmentScrollView(frame: frame);
        self.participantsScrollView.ownerGuid = self.ownerGuid;
        self.view.addSubview(self.participantsScrollView);
    }
    
    func addRequestsScrollView(){
        var verticalMargin:CGFloat = 5;
        var horizontalMargin:CGFloat = 5;
        var originY = self.participantsScrollView.frame.origin.y + self.participantsScrollView.frame.height + verticalMargin;
        
        var origin = CGPoint(x: horizontalMargin, y: originY);
        
        self.requestsTitleLabel = self.setTitleLabel("请求加入的小伙伴", origin: origin);
        self.view.addSubview(self.requestsTitleLabel);
        
        origin.y += (self.requestsTitleLabel.frame.height + 2);
        
        var size = CGSize(width: self.view.frame.width - (horizontalMargin * 2), height: self.view.frame.height * 0.16);
        var frame = CGRect(origin: origin, size: size);
        self.requestScrollView = AppointmentScrollView(frame: frame);
        self.requestScrollView?.ownerGuid = self.ownerGuid;
        self.view.addSubview(self.requestScrollView!);
    }
    
    func setTitleLabel(title:String,origin:CGPoint) -> UILabel{
        var label = UILabel();
        label.frame.origin = origin;
        label.text = title;
        label.textColor = UIColor.whiteColor();
        label.font = Utils.systemFont(14);
        label.sizeToFit();
        return label;
    }
    
    func fillNoteTextView(noteText:String){
        var verticalMargin:CGFloat = 5;
        var horizontalMargin:CGFloat = 5;
        var originY:CGFloat!;
        if(self.requestScrollView == nil){
            originY = self.participantsScrollView.frame.origin.y + self.participantsScrollView.frame.height + verticalMargin
        } else {
            originY = self.requestScrollView!.frame.origin.y + self.requestScrollView!.frame.height + verticalMargin
        }
        
        var height = self.view.frame.height - originY - horizontalMargin;
        var frame = CGRect(x: horizontalMargin, y: originY, width: self.view.frame.width - (horizontalMargin * 2), height: height);
        self.noteTextView = AppointmentNoteTextView(frame:frame);
        self.noteTextView.text = noteText;
        self.noteTextView.font = Utils.systemFont(14);
        self.noteTextView.textColor = UIColor.whiteColor();
        self.noteTextView.backgroundColor = UIColor.clearColor();
        self.noteTextView.editable = false;
        self.view.addSubview(self.noteTextView);
    }
    
    func adjustNoteTextView(){
        if(self.requestScrollView != nil){
            self.noteTextView.frame.origin.y = self.requestScrollView!.frame.origin.y + self.requestScrollView!.frame.height + 5;
        }
    }
    
    
    func setInvitationOperation(){
        var acceptButton = UIButton();
        acceptButton.setBackgroundImage(UIImage(named: "confirm"), forState: UIControlState.Normal);
        acceptButton.showsTouchWhenHighlighted = true;
        acceptButton.sizeToFit();
        acceptButton.addTarget(self, action: Selector("acceptInvitation:"), forControlEvents: UIControlEvents.TouchUpInside);
        var acceptButtonItem = UIBarButtonItem(customView: acceptButton);
        self.navigationItem.rightBarButtonItem  = acceptButtonItem;
    }
    
    func acceptInvitation(sender:UIButton){
        self.inviteesScrollView!.acceptInvitation(self.participantsScrollView);
        self.setLeaveAppointmentOperation();
    }
    
    func setSendJoinRequestOperation(){
        var sendRequestButton = UIButton();
        sendRequestButton.setBackgroundImage(UIImage(named: "add"), forState: UIControlState.Normal);
        sendRequestButton.showsTouchWhenHighlighted = true;
        sendRequestButton.sizeToFit();
        sendRequestButton.addTarget(self, action: Selector("sendJointRequest:"), forControlEvents: UIControlEvents.TouchUpInside);
        var sendRequestButtonItem = UIBarButtonItem(customView: sendRequestButton);
        self.navigationItem.rightBarButtonItem  = sendRequestButtonItem;
    }

    
    func sendJointRequest(sender:UIButton){
        if(self.requestScrollView == nil){
            self.addRequestsScrollView();
            self.adjustNoteTextView();
        }
        
        var url = "/api/v1/appointment/request";
        var httpBody = NSMutableDictionary();
        httpBody.setObject(self.appointmentGuid, forKey: "appointmentGuid");
        self.processing();
        HttpUtils.sendRequest(url, method: RequestMethod.POST, httpBody: httpBody, successHandle: { (response) -> Void in
            var element = response as NSDictionary;
            self.requestScrollView!.moveInto(element, type: ContainerType.Requests,dropTargetView: self.participantsScrollView);
            self.navigationItem.rightBarButtonItem = nil;
            self.processComplete();
            }, errorHandle: { (error) -> Void in
                self.processComplete();
        });
    }
    
    func setLeaveAppointmentOperation(){
        var leaveAppointmentButton = UIButton();
        leaveAppointmentButton.setTitle("退出打球", forState: UIControlState.Normal);
        leaveAppointmentButton.titleLabel?.font = Utils.defaultFont();
        leaveAppointmentButton.sizeToFit();
        leaveAppointmentButton.addTarget(self, action: Selector("leaveAppointment:"), forControlEvents: UIControlEvents.TouchUpInside);
        var leaveAppointmentButtonItem = UIBarButtonItem(customView: leaveAppointmentButton);
        self.navigationItem.rightBarButtonItem  = leaveAppointmentButtonItem;
        
    }
    
    func leaveAppointment(sender:UIButton){
        ConfirmView(message: "确定退出此次约球?", confirm: { () -> Void in
            var userGuid = Utils.currentUserGuid();
            self.participantsScrollView.leaveAppointment(userGuid,moveOutView: nil);
            self.setSendJoinRequestOperation();
            }, cancel: nil).show();
        
    }
    
    func initNavigation(){
        var backButton = UIButton();
        backButton.setBackgroundImage(UIImage(named: "back"), forState: UIControlState.Normal);
        backButton.showsTouchWhenHighlighted = true;
        backButton.sizeToFit();
        backButton.addTarget(self, action: Selector("back:"), forControlEvents: UIControlEvents.TouchUpInside);
        var backBarItem = UIBarButtonItem(customView: backButton);
        self.navigationItem.leftBarButtonItem = backBarItem;
    }
    
    func setChoiceNavigationBarItem(){
        var choiceButton = UIButton();
        choiceButton.setTitle("选择", forState: UIControlState.Normal);
        choiceButton.titleLabel?.font = Utils.defaultFont();
        choiceButton.sizeToFit();
        choiceButton.addTarget(self, action: Selector("choice:"), forControlEvents: UIControlEvents.TouchUpInside);
        var choiceBarItem = UIBarButtonItem(customView: choiceButton);
        self.navigationItem.rightBarButtonItem = choiceBarItem;
    }
    
    func setCancelChoinceNavigationBarItem(){
        var cancelButton = UIButton();
        cancelButton.setTitle("取消", forState: UIControlState.Normal);
        cancelButton.titleLabel?.font = Utils.defaultFont();
        cancelButton.sizeToFit();
        cancelButton.addTarget(self, action: Selector("cancelChoice:"), forControlEvents: UIControlEvents.TouchUpInside);
        var cancelBarItem = UIBarButtonItem(customView: cancelButton);
        self.navigationItem.rightBarButtonItem = cancelBarItem;
    }
    
    // Back
    func back(sender:UIButton){
        self.navigationController?.popViewControllerAnimated(true);
    }
    
    func choice(sender:UIButton){
        self.inviteesScrollView?.readyingChoice();
        self.participantsScrollView.readyingChoice();
        self.requestScrollView?.readyingChoice();
        self.setCancelChoinceNavigationBarItem();
        self.showBottomMenu();
    }
    
    func showBottomMenu(){
        var bottomMenu = BottomMenu();
        bottomMenu.addDeleteCallback(deleteElements);
        bottomMenu.addConfirmCallback(acceptJoinRequest);
        bottomMenu.show();
        self.view.addSubview(bottomMenu);
    }
    
    func acceptJoinRequest(){
        self.requestScrollView?.acceptJoinRequest();
    }
    
    func deleteElements(){
        self.inviteesScrollView?.cancelInvitation();
        self.participantsScrollView.removeFromPanticipantsList();
        self.requestScrollView?.rejectRequest();
    }
    
    func hideBottomMenu(){
        var subviews = self.view.subviews;
        for subview in subviews {
            if(subview is BottomMenu){
                var view = subview as BottomMenu;
                UIView.animateWithDuration(0.3, animations: { () -> Void in
                    view.frame.origin.y += view.frame.height;
                    }, completion: { (complete:Bool) -> Void in
                        for view in subview.subviews{
                            view.removeFromSuperview();
                        }
                        view.removeFromSuperview();
                });
                return;
            }
        }
    }
    
    func cancelChoice(sender:UIButton){
        self.inviteesScrollView?.cancelChoice();
        self.participantsScrollView.cancelChoice();
        self.requestScrollView?.cancelChoice();
        
        self.setChoiceNavigationBarItem();
        self.hideBottomMenu();
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}
